package com.zero.util;


import com.zero.entity.Admin;
import com.zero.entity.FamilyMember;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * jwt的工具类
 */
public class JWTUtil {

    public static String token = "token";
    //秘钥
    public static String jwt_secret="binxin927933474@qq.com.";
    //过期时长
    public static long jwt_expr = 3600*24*1000;

    //生成token（针对管理员）
    public static String sign(Admin admin){

        //1、指定签名的时候使用的签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //2、生成签发时间
        long nowMillis = System.currentTimeMillis();
        Date date = new Date(nowMillis);

        //3、创建playLoad的私有声明
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",admin.getId());
        claims.put("name",admin.getName());
        claims.put("type","ADMIN");
        //4、生成签发人
        String subject = admin.getName();

        JwtBuilder builder = Jwts.builder()
                .setClaims(claims)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(date)
                .setSubject(subject)
                .signWith(signatureAlgorithm,jwt_secret);
        //设置过期时间
        Date exprDate = new Date(nowMillis + jwt_expr);
        builder.setExpiration(exprDate);
        return builder.compact();
    }

    //生成token(针对家庭成员)
    public static String sign(FamilyMember familyMember){

        //1、指定签名的时候使用的签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //2、生成签发时间
        long nowMillis = System.currentTimeMillis();
        Date date = new Date(nowMillis);

        //3、创建playLoad的私有声明
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",familyMember.getId());
        claims.put("name",familyMember.getName());
        claims.put("type","FAMILY_MEMBER");
        //4、生成签发人
        String subject = familyMember.getName();
        JwtBuilder builder = Jwts.builder()
                .setClaims(claims)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(date)
                .setSubject(subject)
                .signWith(signatureAlgorithm,jwt_secret);
        //设置过期时间
        Date exprDate = new Date(nowMillis + jwt_expr);
        builder.setExpiration(exprDate);
        return builder.compact();
    }

    //验证token
    public static boolean verify(String token){
        try {
            if(StringUtils.isEmpty(token)){
                return false;
            }
            //解析token
            Jwts.parser().setSigningKey(jwt_secret).parseClaimsJws(token).getBody();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //返回token中设置的类型
    public static String getType(String token){
        try {
            if(StringUtils.isEmpty(token)){
                throw new RuntimeException("token不能为空");
            }
            if(verify(token)){
                Claims claims = Jwts.parser().setSigningKey(jwt_secret).parseClaimsJws(token).getBody();
                return claims.get("type")+"";
            }else{
                throw new RuntimeException("超时或不合法token");
            }
        } catch (Exception e) {
            throw new RuntimeException("超时或不合法token");
        }
    }

    //通过token获取管理员信息
    public static Admin getAdmin(String token){
        try {
            if(StringUtils.isEmpty(token)){
                throw new RuntimeException("token不能为空");
            }
            if(verify(token)){
                //通过私钥解析token里放置的东西
                Claims claims = Jwts.parser().setSigningKey(jwt_secret).parseClaimsJws(token).getBody();

                //获取token中的数据
                Admin admin = new Admin();
                admin.setId(Integer.parseInt(claims.get("id")+""));
                admin.setName(claims.get("name")+"");

                return admin;
            }else{
                throw new RuntimeException("超时或不合法token");
            }
        } catch (Exception e) {
            throw new RuntimeException("超时或不合法token");
        }
    }

    //通过token获取家庭成员的信息
    public static FamilyMember getFamilyMember(String token){
        try {
            if(StringUtils.isEmpty(token)){
                throw new RuntimeException("token不能为空");
            }
            if(verify(token)){
                Claims claims = Jwts.parser().setSigningKey(jwt_secret).parseClaimsJws(token).getBody();

                FamilyMember familyMember = new FamilyMember();
                familyMember.setId(Integer.parseInt(claims.get("id")+""));
                familyMember.setName(claims.get("name")+"");

                return familyMember;
            }else{
                throw new RuntimeException("超时或不合法token");
            }
        } catch (Exception e) {
            throw new RuntimeException("超时或不合法token");
        }
    }


    public static void main(String[] args) {
        Admin admin = new Admin();
        admin.setId(123);
        admin.setName("zero");
        System.out.println(admin);

        String sign = sign(admin);
        System.out.println(sign);

        System.out.println(verify(sign));

        //System.out.println(verify("sadasd"));
        System.out.println(getType(sign));

        System.out.println(getAdmin(sign));
        //System.out.println(sign(admin));
    }

}